
const ncname = `[a-zA-Z_][\\-\\.0-9_a-zA-Z]*`; // abc-aaa
const qnameCapture = `((?:${ncname}\\:)?${ncname})`; // <aaa:asdads>
const startTagOpen = new RegExp(`^<${qnameCapture}`); // 标签开头的正则 捕获的内容是标签名
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`); // 匹配标签结尾的 </div>
const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; // 匹配属性的
const startTagClose = /^\s*(\/?)>/; // 匹配标签结束的 >  <div>
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g

let root = null;
let currentParent = null;
let ELEMENT_TYPE = 1;
let TEXT_TYPE = 3;
let stack = [];

function createASTElement(tagName,attrs){
  return {
    tag: tagName,
    attrs,
    parent:null,
    type: ELEMENT_TYPE,
    children: []
  }
}
function start(tagName,attrs){
  let element = createASTElement(tagName,attrs);
  if(!root){
    root = element;
  }
  currentParent = element; 
  stack.push(element);
  // console.log('开始标签：',tagName,'属性是：',attrs);
}
function chars(text){
  text = text.replace(/\s/g,'');
  if(text){
    currentParent.children.push({
      text,
      type:TEXT_TYPE
    })
  }
}
function end(tagName){
  console.log('结束标签：',tagName);
  let element = stack.pop();

  currentParent = stack[stack.length - 1];
  if(currentParent){
    element.parent = currentParent;
    currentParent.children.push(element);
  }
}


export function parseHTML(html){
    while(html){
      let textEnd = html.indexOf('<');
      if(textEnd == 0){
          let startTagMatch = parseStartTag();
          if(startTagMatch){
            start(startTagMatch.tagName,startTagMatch.attrs);
            continue;
          }
          let endTagMatch = html.match(endTag);
          if(endTagMatch){
            advance(endTagMatch[0].length);
            end(endTagMatch[1]);
            continue;
          }

      }
      let text;
      if(textEnd >=0){
        text = html.substring(0,textEnd);
      }
      if(text){
        advance(text.length);
        chars(text);
      }
    }
  
    function advance(n) {
      html = html.substring(n);
    }
    function parseStartTag() {
      let start = html.match(startTagOpen);
      if (start) {
          const match = {
              tagName: start[1],
              attrs: []
          }
          advance(start[0].length); // 将标签删除
          let end, attr;
          while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
              // 将属性进行解析
              advance(attr[0].length); // 将属性去掉
              match.attrs.push({
                  name: attr[1],
                  value: attr[3] || attr[4] || attr[5]
              });
          }
          if (end) { // 去掉开始标签的 >
              advance(end[0].length);
              return match
          }
      }
    }
    return root;
}
